package modbus

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"net"
)

// 处理 Modbus 请求和响应
func handleModbusRequest(conn net.Conn) {
	defer conn.Close()

	buffer := make([]byte, 256)
	_, err := conn.Read(buffer)
	if err != nil {
		fmt.Println("Error reading from connection:", err)
		return
	}

	// 解析 Modbus TCP 请求
	transactionID := binary.BigEndian.Uint16(buffer[0:2])
	protocolID := binary.BigEndian.Uint16(buffer[2:4])
	length := binary.BigEndian.Uint16(buffer[4:6])
	unitID := buffer[6]
	functionCode := buffer[7]

	fmt.Printf("Transaction ID: %d\n", transactionID)
	fmt.Printf("Protocol ID: %d\n", protocolID)
	fmt.Printf("Length: %d\n", length)
	fmt.Printf("Unit ID: %d\n", unitID)
	fmt.Printf("Function Code: %d\n", functionCode)

	// 构造 Modbus TCP 响应
	response := new(bytes.Buffer)
	binary.Write(response, binary.BigEndian, transactionID)
	binary.Write(response, binary.BigEndian, protocolID)
	binary.Write(response, binary.BigEndian, uint16(3+1+1)) // 长度字段，固定响应长度（包含字节数量）
	binary.Write(response, binary.BigEndian, unitID)

	switch functionCode {
	case 1: // 读取线圈状态 (功能码1)
		// 返回模拟数据
		response.WriteByte(1)    // 字节数
		response.WriteByte(0xFF) // 线圈状态：全开
	case 3: // 读取保持寄存器 (功能码3)
		// 返回模拟数据
		response.WriteByte(2)    // 字节数
		response.WriteByte(0x00) // 寄存器值高字节
		response.WriteByte(0x01) // 寄存器值低字节
	default:
		fmt.Println("Unsupported function code")
		return
	}

	_, err = conn.Write(response.Bytes())
	if err != nil {
		fmt.Println("Error writing to connection:", err)
		return
	}
}

func main() {
	listener, err := net.Listen("tcp", ":502")
	if err != nil {
		fmt.Println("Error starting server:", err)
		return
	}
	defer listener.Close()

	fmt.Println("Modbus TCP Slave server started on :502")

	for {
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println("Error accepting connection:", err)
			continue
		}
		go handleModbusRequest(conn)
	}
}
